跳到主要内容

SpringCloud Sidecar 调用第三方服务的适配器

Sidecar 是什么?

官方文档 实现多语言支持,就是一个适配器,用来接入第三方模块(或者其他语言编写的模块)

配置环境

引入模块

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-sidecar</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

编写配置文件

server:
port: 7071

spring:
application:
name: sidecar

# 把服务注册进 Eureka
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/

# 指定代理的第三方服务
sidecar:
port: 8091
ip-address: 127.0.0.1

然后在启动类上加入 @EnableSidecar 注解

可以不用放:@EnableEurekaClient 因为 @EnableSidecar 内涵了

@SpringBootApplication
@EnableSidecar
public class StudySidecarApplication {

public static void main(String[] args) {
SpringApplication.run(StudySidecarApplication.class, args);
}

}

调用服务

在客户端创建 FeignClient

// 绑定前面的 sidecar 代理服务
@FeignClient("sidecar")
public interface OtherServiceClient {
@GetMapping("/other")
String getOther();
}

在 Controller 调用

@Autowired
private OtherServiceClient otherServiceClient;

// 调用第三方服务
@GetMapping("/other")
public String getOther() {
return otherServiceClient.getOther();
}

然后就能访问到这个第三方服务了

# 这里通过 Zuul 访问的
http://localhost:8085/v1/customer/other